package com.qianda.qdminiapp.controller;

import com.qianda.qdminiapp.common.exception.ExceptionCode;
import com.qianda.qdminiapp.common.exception.SimpleException;
import com.qianda.qdminiapp.security.InvalidTokenException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName ExceptionAdviceController
 * @Author cw
 * @Date 2019/8/14 11:49
 * @Version 1.0
 */
@ControllerAdvice
public class ExceptionAdviceController  {

        @ExceptionHandler(value = Exception.class)
        @ResponseBody
        public Result DefultException(HttpServletRequest request, Exception e){
            e.printStackTrace();
            //没有权限
            if(e instanceof InvalidTokenException){
                return Result.failure(ExceptionCode.EX_HTTP_NO_PERM.code(),ExceptionCode.EX_HTTP_NO_PERM.message(),null);
            }

            return Result.failure(ExceptionCode.EX_SYSTEM.code(),ExceptionCode.EX_SYSTEM.message(),null);
        }

        /**
         *
         * 功能描述:  业务异常
         *
         * @param:
         * @return:
         * @auther: cw
         * @date: 2019/7/5 23:10
         */
        @ExceptionHandler(value = SimpleException.class)
        @ResponseBody
        public Result SimpleException(HttpServletRequest request, SimpleException e){
            e.printStackTrace();
            return translateResult(e.code());
        }


        private Result translateResult(ExceptionCode code) {
            return translateResult(code, null);
        }

        /**
         * 将异常码转换为结果对象
         *
         * @param code 异常码
         * @param data 额外的数据
         * @return 结果对象
         */
        private Result translateResult(ExceptionCode code, Object data) {
            return Result.failure(code.code(), code.message(), data);
        }

        /**
         * 将异常转换为结果对象
         *
         * @param ex 异常
         * @return 结果对象
         */
        private Result translateResult(SimpleException ex) {

            ExceptionCode code = ex.code();
            String[] args = ex.args();

            String message = code.message();
            if (args != null) {
                message = String.format(message, args);
            }

            return Result.failure(code.code(), message);
        }

}
